package org.budo.phone.location.service.taobao;

import java.nio.charset.Charset;

import org.budo.phone.location.service.api.AbstractBudoPhoneLocation;
import org.budo.phone.location.service.api.BudoPhoneLocation;
import org.budo.phone.location.service.api.BudoPhoneLocationService;
import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.lang.util.StringUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class TaobaoPhoneLocationService implements BudoPhoneLocationService {
    private static final String API_URL = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";

    // https://m.baidu.com/s?word=13785227813
    @Override
    public BudoPhoneLocation seekPhoneLocation(String phone) {
        try {
            return this.seek(phone);
        } catch (Throwable e) {
            log.error("#25 phone=" + phone + ", this=" + this + ", e=" + e, e);
            return null;
        }
    }

    private BudoPhoneLocation seek(String phone) {
        Request request = new Request();
        request.setUrl(API_URL);
        request.setParameter("tel", phone);

        Response response = request.execute();
        String responseBody = response.getBody(Charset.forName("GBK"));
        if (response.getStatus() > 200 || StringUtil.isEmpty(responseBody)) {
            log.error("#25 request=" + request + ", response=" + response);
            return null;
        }

        return this.responseToLocation(phone, responseBody);
    }

    private BudoPhoneLocation responseToLocation(String phone, String responseBody) {
        if (StringUtil.isNullOrEmpty(responseBody)) {
            log.error("#50 responseBody is null, responseBody=" + responseBody + ", phone=" + phone);
            return null;
        }

        responseBody = responseBody.replace("__GetZoneResult_ = ", "").trim();

        if (!responseBody.startsWith("{")) {
            log.error("#60 responseBody = " + responseBody);
            return null;
        }

        JSONObject jsonObject = JSON.parseObject(responseBody);
        // __GetZoneResult_ = {
        // province:'浙江',
        // catName:'中国移动',
        // }

        String serviceProvider = jsonObject.getString("catName");
        String province = jsonObject.getString("province");
        if (StringUtil.isNullOrEmpty(serviceProvider) || StringUtil.isNullOrEmpty(province)) {
            log.info("#73 return null, phone=" + phone + ", responseBody=" + responseBody);
            return null;
        }

        return new AbstractBudoPhoneLocation(province, null, serviceProvider);
    }
}